import axios from 'axios';
import {Message} from 'element-ui';
import qs from "qs";
import {urls} from './urls';
import {format} from './format';
import Base64 from '@/publicMethod/byBase64';
import {localUitl} from "../utils/localUitl";

let base = new Base64();

const service = axios.create({
  timeout: 30000,
  withCredentials: false, // 是否允许带cookie这些
  headers: {
    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
  }
})


// 添加请求拦截器
service.interceptors.request.use(
  config => {
    console.log("request", config);
    if (config.url.indexOf("pwdLogin") == -1 && config.url.indexOf("leftMenu") == -1 && config.headers.sendKey != "getUserN") {
      config.headers["access_token"] = localUitl.getToken();
    }

    if (config.headers.sendKey == "getDownload") {
      config.timeout = 0
    }

    return config;
  },
  error => {
    return Promise.reject(error.data.error.message);
  }
);

//返回状态判断(添加响应拦截器)
service.interceptors.response.use(
  res => {
    console.log("response", res);
    let sendKey = res.config.headers.sendKey;
    //TODO 看是否需要格式化逻辑处理
    if (format[sendKey]) {
      return format[sendKey](res);
    } else {
      return res;
    }
  },
  error => {
    // let data = error.response.data;
    // Message({
    //   message: data || error.message,
    //   type: 'error'
    // })
    return Promise.reject(error);
  }
);

export const https = {};
for (let [method, mapObj] of urls) {
  if (!https[method]) {
    https[method] = {};
  }
  for (let [key, url] of mapObj) {
    https[method][key] = function (params) {
      const config = {
        method: method,
        url: url,
        params: null,
        headers: {
          sendKey: key
        },
        data: null
        // baseURL: host
      }
      switch (method) {
        case "get":
          if (config.url.indexOf("./static") != -1) {
            config.baseURL = "./";
          }
          config.params = params;
          break;
        case "post":
          let obj = {};
          if (config.headers.sendKey == "getFile" ||
            config.headers.sendKey == "getDeleteFile" ||
            config.headers.sendKey == "getDownload" ||
            config.headers.sendKey == "getHdfs") {
            obj = {
              ...params,
              access_token: localUitl.getToken()
            }
          } else {
            obj = {
              ...params
            }
          }
          if (config.headers.sendKey == "upload") {
            config.baseURL = "";
          }

          // 判断是不是下载文件的接口 要添加响应类型
          // if (config.headers.sendKey == "getDownload") {
          //   config.responseType = 'blob';
          // }
          config.data = qs.stringify(obj);
          break;
      }
      return service(config);
    }
  }
}




